<?php

Yii::import('application.extensions.NuSoap.NSoapServerController');
Yii::import('application.modules.adviser.models.SearchForm');

class DefaultController extends NSoapServerController
{

	public function __construct($id,$module=null)
	{
		parent::__construct($id, 'DefaultController', $module);
	}
	
	
/**********************************************************************************************************************
 * LOGIN SERVICE
 */
	/**
	 * Login into Harliane.
	 *
	 * @param string $username
	 * @param string $password
	 * @return string User information
	 * @soap
	 */
	public function login($username, $password) {
		$form = new LoginForm();
		$form->username = $username;
		$form->password = $password;

		if(!$form->validate()) {
			$errors = array();
			foreach ($form->errors as $field=>$error) {
				$errors[] = "$field={".join(",", $error)."}";
			}
			throw new CException(join("\n", $errors), 500);
		}

		$session=new CHttpSession;
		$session->open();
		$hUser = new HUser();
		$hUser->attributes = Yii::app()->user->getState('dbuser')->attributes;
		$session['user'] = $hUser;

		$res = new HSession();
		$res->user = $session['user'];
		$res->session_id = $session->getSessionID();
		$res->session_name = $session->getSessionName();

		$res->roles = array();
		$roles = Yii::app()->authManager->getAuthAssignments($username);

		foreach ($roles as $role) {
			$tasks = Yii::app()->authManager->getAuthItem($role->itemName)->getChildren();
			foreach($tasks as $task) {
				$res->roles[] = $task->name;
			}
		}
		
		return json_encode($res);
	}

	/**
	 * Close user session
	 *
	 * @return boolean if session has been closed.
	 * @soap
	 */
	public function logout(){
		$session=new CHttpSession;
		return $session->closeSession();
	}

	/**
	 * Update current user account information
	 *
	 * @param string $password
	 * @param string $user
	 * @throws CException
	 *
	 * @return string
	 * @soap
	 */
	public function updateAccountInformations($password, $user) {
		$session=new CHttpSession;
		if (!$session->contains('user')) {
			$session->close();
			throw new CException("You have to logged in before.", 500);
		}
		
		$user = json_decode($json, true);

		$form = new InformationForm();
		$form->attributes = $user;
		$form->password = $password;

		$form->save();
		if ($form->hasErrors()) {
			$errors = array();
			foreach ($form->errors as $field=>$error) {
				$errors[] = "$field={".join(",", $error)."}";
			}
			throw new CException(join("\n", $errors), 500);
		}

		return $this->login(Yii::app()->user->id, $password);
	}

	/**
	 * Update current user password
	 *
	 * @param string $password
	 * @param string $password_new
	 * @param string $password_check
	 *
	 * @return string
	 * @soap
	 */
	public function changePassword ($password, $password_new, $password_check) {
		$session=new CHttpSession;
		if (!$session->contains('user')) {
			$session->close();
			throw new CException("You have to logged in before.", 500);
		}

		$form = new PasswordForm();
		$form->password = $password;
		$form->password_new = $password_new;
		$form->password_check = $password_check;

		$form->save();
		if ($form->hasErrors()) {
			$errors = array();
			foreach ($form->errors as $field=>$error) {
				$errors[] = "$field={".join(",", $error)."}";
			}
			throw new CException(join("\n", $errors), 500);
		}

		return $this->login(Yii::app()->user->id, $password_new);
	}

/**********************************************************************************************************************
 * PARAMETER SERVICE
 */

	/**
	 * Gets all available languages in Harliane.
	 *
	 * @return string (HLanguage[]) All available languages.
	 * @soap
	 */
	public function findAllLanguages() {
		$langs = array();

		foreach (Constants::userLanguages() as $code => $label) {
			$lang = new HLanguage();
			$lang->code = $code;
			$lang->label = $label;
			$langs[] = $lang;
		}

		return json_encode($langs);
	}

	/**
	 * @return string (HMapEntry[]) All countries.
	 * @soap
	 */
	public function findAllCountries() {
		$countries = array();

		foreach (Country::model()->findAll() as $country) {
			$entry = new HMapEntry();
			$entry->key = $country->country_mnemonic;
			$entry->value = $country->country_name;
			$countries[] = $entry;
		}

		return json_encode($countries);
	}

	/**
	 * @param integer $id
	 * 
	 * @return string (HCity) City.
	 * 
	 * @soap
	 */
	public function findCityById($id) {
		$city = City::model()->findByPk($id);
		if ($city != null) {
			$res = new HCity();
			$res->attributes = $city->attributes;
			return json_encode($res);
		}
		return null;
	}

	/**
	 * @return string (HSearchParameter[])
	 * @soap
	 */
	public function getAllSearchParameters() {
		$session=new CHttpSession;
		if (!$session->contains('user')) {
			$session->close();
			throw new CException("You have to logged in before.", 500);
		}

		$arr = new SearchForm();
		$arr = $arr->getColumnsList();
		$res = array();

		foreach ($arr['labels'] as $name=>$label) {
			$l = new HSearchParameter();
			$l->columnName = $name;
			$l->columnLabel = $label;
			$l->type = $arr['types'][$name];
			
			$l->values = array();
			if (is_array($arr['values'][$name])) {
				foreach($arr['values'][$name] as $values) {
					$map = new HMapEntry();
					$map->key = $values['id'];
					$map->value = $values['label'];
					$l->values[] = $map;
				}
			}
			
			$res[] = $l;
		}

		return json_encode($res);
	}
	
	public function findAllRoutes (){
		
	}
	
	
	public function findAllServices (){
		
	}
	
	
/**********************************************************************************************************************
 * PROJECT SERVICE
 */

	/**
	 * @param string $parameters (HSearchFilter[])
	 * @return string (HSearchItem[])
	 * @soap
	 */
	public function search($parameters) {
		$session=new CHttpSession;
		if (!$session->contains('user')) {
			$session->close();
			throw new CException("You have to logged in before.", 500);
		}

		$form = new SearchForm(); 
		$attributes = array('column' => array(), 'operator' => array(), 'value' => array());
		$parameters = json_decode($parameters, true);
		foreach ($parameters as $parameter) {
			$attributes['columns'][$parameter['column']] = $parameter['column'];
			$attributes['operator'][$parameter['column']] = $parameter['operator'];
			$attributes['value'][$parameter['column']] = $parameter['value'];
		}
		$form->attributes = $attributes;
		
		$criteria = $form->buildCriteria();
		
		$results = SearchItem::model()->findAll($criteria);
		
		$res = array();
		
		foreach($results as $result) {
			$r = new HSearchItem();
			$r->attributes = $result->attributes;
			$res[] = $r;
		}
		
		return json_encode($res);
	}
	
	/**
	 * @param integer $id
	 * @return HProject
	 * @soap
	 */
	public function getProject($id) {
		$session=new CHttpSession;
		if (!$session->contains('user')) {
			$session->close();
			throw new CException("You have to logged in before.", 500);
		}
			
		$project = Project::model()->findByPk($id);
		if (project == null) {
			throw new CException ("Cannot find project #" . $id);
		}
		
		$owner = $project->owner;
		$topics = $project->topics;
		$meetings = $project->meetings;
		
		$p = new HProject();
		$p->attributes = $project->attributes;
		$p->owner = new HOwner();
		$p->owner->attributes = $project->owner->attributes;
		if (is_array($project->owner->specific_data)) {
			$data = array();
			foreach ($project->owner->specific_data as $m) {
				$datum = new HOwnerSpecificData();
				$datum->attributes = $m->attributes;
				$data[] = $datum;
			}
			$p->owner->specific_data = $data;
		}
		if (is_array($project->meetings)) {
			$meetings = array();
			foreach ($project->meetings as $m) {
				$meeting = new HMeetings();
				$meeting->attributes = $m->attributes;
				$meeting->meeting_comment = $m->attributes;
				$meetings[] = $meeting;
			}
			$p->meetings = $meetings;
		}
		if (is_array($project->topics)) {
			$topics = array();
			foreach ($project->topics as $m) {
				$topic = new HProjectTopic();
				$topic->attributes = $m->attributes;
				$topics[] = $topic;
			}
			$p->topics = $topics;
		}
		
		return $p;
	}

	/*
	 * List all users
	 *
	 * @return HUser[] Users informations
	 * @soap
	 */
	public function findAllUsers() {
		$session=new CHttpSession;
		if (!$session->contains('user')) {
			$session->close();
			throw new CException("You have to logged in before.", 500);
		}
			
		$users = User::model()->findAll();
		$hUsers = array();
		foreach ($users as $user) {
			$hUser = new HUser();
			$hUser->attributes = $user->attributes;
			$hUsers[] = $hUser;
		}

		return $hUsers;
	}

}